<script setup>
import newLoading from '@/components/newLoading/index.vue';
import Toast from "@vant/weapp/dist/toast/toast";
import myCanvas from '@/utils/myCanvas'
import { imgUploadVerify } from '@/utils/auth'
import { getCategoryDetail } from '@/api/home'
import { imgInpaint, editImgUpload, maskImgUpload, getImageByTaskId } from '@/api/painting'
import { ref, nextTick } from 'vue'
import { onLoad, onReady, onUnload } from '@dcloudio/uni-app'

// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 页面参数
const queryParams = ref({})
// 提交数据
const queryData = ref({})
// 消耗算力
const expendNum = ref(0)


const queryData2 = ref({})


let imgCanvas, smearCanvas, eraseCanvas


// 原图尺寸
const oldImgSize = ref({})

// 父盒子宽高
const contentDom = ref({})
// canvas宽高
const canvasDom = ref({})

// 是否正在绘制(画笔)
const isDrawing = ref(false);
// 记录上一个点
const lastPoint = ref({});
// 是否是橡皮擦模式
const isErase = ref(false);
// 橡皮擦位置
const eraserPosition = ref({ x: 0, y: 0 });
// 橡皮擦/线条大小
const sliderValue = ref(30)

// 任务id
const taskId = ref('')
let timer = null


const loading = ref(false);
const loadingRef = ref(null);





// 清除图片
function clearImg() {
    queryParams.value.imageFileUrl = ''
    imgCanvas.clearRect(0, 0, canvasDom.value.width, canvasDom.value.height)
    smearCanvas.clearRect(0, 0, canvasDom.value.width, canvasDom.value.height)
}

// 调整橡皮擦线条大小
function sliderDrag(e) {
    sliderValue.value = e.detail.value
}

// 手指抬起
function touchend() {
    isDrawing.value = false;
    eraseCanvas.clearRect(0, 0, eraseCanvas.canvas.width, eraseCanvas.canvas.height)
}


// 触摸移动
function touchmove(e) {
    if (!isDrawing.value) return
    // 画笔
    if (!isErase.value) {
        const newPoint = e.touches[0]; // 记录当前点
        smearCanvas.drawBrush(lastPoint.value.x, lastPoint.value.y, newPoint.x, newPoint.y, sliderValue.value, '#FFF')

        eraseCanvas.clearRect(0, 0, eraseCanvas.canvas.width, eraseCanvas.canvas.height)
        eraseCanvas.drawRoundedRect(newPoint.x, newPoint.y, sliderValue.value, sliderValue.value / 2, 'rgba(0,0,0,0.5)')

        lastPoint.value = newPoint; // 更新上一个点
    } else {
        const newPoint = e.touches[0]; // 记录当前点
        smearCanvas.smoothErase(lastPoint.value.x, lastPoint.value.y, newPoint.x, newPoint.y, sliderValue.value)
        eraseCanvas.clearRect(0, 0, eraseCanvas.canvas.width, eraseCanvas.canvas.height)
        eraseCanvas.drawRoundedRect(newPoint.x, newPoint.y, sliderValue.value, sliderValue.value / 2, 'rgba(0,0,0,0.5)')
        lastPoint.value = newPoint; // 更新上一个点
    }
}



// 触摸事件
function touchstart(e) {
    if (!queryParams.value.imageFileUrl) return
    isDrawing.value = true;
    lastPoint.value = e.touches[0]; // 记录起点
    eraserPosition.value = {
        x: e.touches[0].x,
        y: e.touches[0].y
    }
}




// 页面跳转
function toPage() {
    let verify = queryParams.value.imageFileUrl && queryData.value.imageFileUrl && queryParams.value.imageFileUrl === queryData.value.imageFileUrl
    if (verify) {
        return uni.navigateTo({
            url: `/newEditionDraw/eliminate/detail/index?data=${JSON.stringify(queryData2.value)}`
        })
    }
    Toast.fail("请先进行涂抹消除");
}


// 开始消除
async function startFn() {
    clearInterval(timer);
    if (!queryParams.value.imageFileUrl) {
        return Toast.fail("请先上传修改图片");
    }
    if (!smearCanvas.hasDrawn(0, 0, smearCanvas.canvas.width, smearCanvas.canvas.height)) {
        return Toast.fail("请先进行涂抹消除");
    }
    await exportCanvasImage()
    loading.value = true
    await editImgUploadFn()
    await maskImgUploadFn()
    imgInpaintFn()
}



// 获取任务状态
async function getImageByTaskIdFn() {
    const res = await getImageByTaskId(taskId.value)
    if (res.data.state === 1) {
        clearInterval(timer);
        await loadingRef.value.completeLoading()
        clearImg()
        res.data.title = queryItem.value.title
        queryData2.value = res.data
        queryParams.value.imageFileUrl = queryData.value.imageFileUrl = res.data.imgPath
        drawImage()
    } else if (![3, 4].includes(res.data.state)) {
        clearInterval(timer);
        const errorMessage = res.data.remark.split('失败原因')[1]
        Toast.fail(errorMessage);
        loading.value = false
    }
}



// 图像消除任务提交
async function imgInpaintFn() {
    try {
        const res = await imgInpaint(queryData.value)
        taskId.value = res.data.taskId
        timer = setInterval(() => {
            getImageByTaskIdFn()
        }, 2000);

    } catch (error) {
        loading.value = false
        Toast.fail(error.data?.message);
    }
}




// 导出canvas图片
function exportCanvasImage() {
    return new Promise(resolve => {
        uni.canvasToTempFilePath({
            canvas: smearCanvas.canvas,
            destWidth: oldImgSize.value.width,
            destHeight: oldImgSize.value.height,
            success(res) {
                queryParams.value.imageMaskFileUrl = res.tempFilePath
                resolve()
            },
        })
    })
}


// 蒙版层图片上传
function maskImgUploadFn() {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await maskImgUpload({
                orgImgUrl: queryData.value.imageFileUrl,
                maskType: 9,
                maskImg: queryParams.value.imageMaskFileUrl,
            })
            queryData.value.imageMaskFileUrl = res
            resolve()
        } catch (error) {
            loading.value = false
            reject()
        }
    })
}


// 上传原图
function editImgUploadFn() {
    return new Promise(async (resolve, reject) => {
        let url = ''
        if (queryParams.value.imageFileUrl.includes('https://')) {
            const res = await uni.getImageInfo({
                src: queryParams.value.imageFileUrl,
            })
            url = res.path
        } else {
            url = queryParams.value.imageFileUrl
        }

        try {
            const res = await editImgUpload({
                type: 2,
                orgImg: url
            })
            queryData.value.imageFileUrl = res.orgImgUrl
            resolve()
        } catch (error) {
            loading.value = false
            reject()
        }

    })

}



// 上传图片
async function uplaodImgFn() {
    const res = await imgUploadVerify()
    queryParams.value.imageFileUrl = res
    imgCanvas.clearRect(0, 0, canvasDom.value.width, canvasDom.value.height)
    smearCanvas.clearRect(0, 0, canvasDom.value.width, canvasDom.value.height)
    eraseCanvas.clearRect(0, 0, canvasDom.value.width, canvasDom.value.height)
    calculatePicAspectRatio(queryParams.value.imageFileUrl).then(() => {
        drawImage()
    })
}

// 绘制图片
function drawImage() {
    nextTick(() => {
        imgCanvas.init()
        smearCanvas.init()
        eraseCanvas.init()
        setTimeout(() => {
            imgCanvas.drawImage(queryParams.value.imageFileUrl, 0, 0, canvasDom.value.width, canvasDom.value.height)
        }, 1000)
    })

}



// 加载关闭事件
function loadingClose() {
    clearInterval(timer);
}



// 计算图片宽高比及外部边框盒子的宽高
async function calculatePicAspectRatio(path) {
    const { width, height } = await uni.getImageInfo({ src: path })
    oldImgSize.value = {
        width,
        height
    }
    const widthRatio = contentDom.value.width / width;
    const heightRatio = contentDom.value.height / height;
    const scaleRatio = Math.min(widthRatio, heightRatio);


    // 计算缩放后的图片宽度和高度
    const scaledWidth = width * scaleRatio;
    const scaledHeight = height * scaleRatio;

    canvasDom.value = {
        width: scaledWidth,
        height: scaledHeight
    }
}


// 获取分类详情
async function getCategoryDetailFn() {
    const res = await getCategoryDetail(queryItem.value.id)
    queryInfo.value = res.data
    dataConversion()
}


// 数据转换
function dataConversion() {
    queryInfo.value.categoryParam.forEach(item => {
        if (item.title === 'expendNum') {
            expendNum.value = item.data[0].title
        }
    })
}


onUnload(() => {
    clearInterval(timer);
    loading.value = false
})


onReady(() => {
    uni.createSelectorQuery().select('.canvas_box').boundingClientRect((res) => {
        contentDom.value.width = res.width
        contentDom.value.height = res.height
        imgCanvas = new myCanvas('imgCanvas')
        smearCanvas = new myCanvas('smearCanvas')
        eraseCanvas = new myCanvas('eraseCanvas')
    }).exec()
})


onLoad(async (e) => {
    if (e.item) {
        queryItem.value = JSON.parse(e.item)
        getCategoryDetailFn()

        if (!queryItem.value.imageFileUrl) return
        await nextTick()

        const res = await uni.getImageInfo({
            src: queryItem.value.imageFileUrl,
        })
        queryParams.value.imageFileUrl = res.path
        setTimeout(() => {
            imgCanvas.clearRect(0, 0, canvasDom.value.width, canvasDom.value.height)
            smearCanvas.clearRect(0, 0, canvasDom.value.width, canvasDom.value.height)
            eraseCanvas.clearRect(0, 0, canvasDom.value.width, canvasDom.value.height)
            calculatePicAspectRatio(queryParams.value.imageFileUrl).then(() => {
                drawImage()
            })
        }, 600)
    }
})
</script>

<template>
    <div class='eliminate'>
        <NavBar :zIndex="5">AI消除</NavBar>
        <div class="container">
            <div class="canvas_box">
                <!--上传按钮-->
                <div class="upload_btn" v-if="!queryParams.imageFileUrl" @click="uplaodImgFn">
                    <i class="iconfont ai-icon-shangchuancankaotu"></i>
                    <div class="text">相册选择</div>
                </div>
                <!--删除-->
                <div v-else class="clearBox" @click="clearImg">
                    <i class="iconfont ai-icon-shanchutupian"></i>
                </div>
                <canvas type="2d" id="imgCanvas" :style="{ width: `${canvasDom.width}px`, height: `${canvasDom.height}px` }"
                    class="imgCanvas"></canvas>
                <canvas type="2d" id="smearCanvas"
                    :style="{ width: `${canvasDom.width}px`, height: `${canvasDom.height}px` }"
                    class="smearCanvas"></canvas>

                <canvas type="2d" id="eraseCanvas"
                    :style="{ width: `${canvasDom.width}px`, height: `${canvasDom.height}px` }" class="eraseCanvas"
                    @touchstart="touchstart" @touchmove.stop="touchmove" @touchend="touchend"></canvas>
            </div>
        </div>
        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <div class="footer_content_top">
                    <i class="iconfont ai-icon-a-shibieleixingqueren" @click="toPage"></i>
                </div>

                <div class="eraseAndsmear">
                    <div class="left" @click="isErase = !isErase">
                        <div class="smear" :class="{ active: !isErase }">
                            <i class="iconfont ai-icon-tumo"></i>
                        </div>
                        <div class="erase" :class="{ active: isErase }">
                            <i class="iconfont ai-icon-cachu"></i>
                        </div>
                    </div>
                    <div class="right">
                        <van-slider :value="sliderValue" :min="15" :max="45" @drag="sliderDrag" bar-height="4px"
                            active-color="#83CD88" />
                    </div>
                </div>
                <div class="create_btn">
                    <myDrawButton :expendNum="expendNum" @click="startFn">开始消除</myDrawButton>
                </div>
            </div>
        </div>
    </div>
    <van-toast id="van-toast" />
    <newLoading ref="loadingRef" v-model="loading" :duration="10000" :label="['排队中，预计等待10秒']" @close="loadingClose">
    </newLoading>
</template>

<style lang='scss' scoped>
.eliminate {
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .container {
        flex: 1;
        padding: 30rpx;

        .canvas_box {
            position: relative;
            height: 100%;
            background: var(--a-main-box-bg-color);
            border-radius: 20rpx;
            overflow: hidden;

            .upload_btn {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                z-index: 10;
                width: 228rpx;
                height: 84rpx;
                border-radius: 45rpx;
                border: 3rpx solid var(--a-main-color);
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 10rpx;

                .iconfont {
                    font-size: 32rpx;
                    color: var(--a-one-text-color);
                }

                .text {
                    font-size: 32rpx;
                    color: var(--a-one-text-color);
                }
            }

            .clearBox {
                position: absolute;
                bottom: 20rpx;
                right: 20rpx;
                z-index: 999;
                color: var(--a-one-text-color);
                width: 59rpx;
                height: 59rpx;
                background-color: #fff;
                background: rgba(0, 0, 0, 0.3);
                border-radius: 50%;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;

                .iconfont {
                    font-size: 36rpx;
                }

                .anewUpload {
                    font-size: 22rpx;
                }
            }

            .imgCanvas {
                z-index: 2;
            }

            .smearCanvas {
                z-index: 3;
            }

            .eraseCanvas {
                z-index: 4;
            }


            .bgCanvas,
            .imgCanvas,
            .smearCanvas,
            .eraseCanvas {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    .footer {
        .footer_placeholder {
            height: 350rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 350rpx;
            background: var(--a-main-tabNav-bg-color);
            padding: 28rpx 30rpx 30rpx;


            .footer_content_top {
                display: flex;
                align-items: center;
                justify-content: flex-end;

                .iconfont {
                    font-size: 36rpx;
                    color: var(--a-one-text-color);
                }
            }

            .eraseAndsmear {
                display: flex;
                align-items: center;
                gap: 26rpx;
                margin-top: 10rpx;

                .left {
                    flex-shrink: 0;
                    width: 170rpx;
                    height: 66rpx;
                    background: var(--a-main-box-bg-color);
                    border-radius: 33rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    .smear,
                    .erase {
                        width: 82rpx;
                        height: 60rpx;
                        border-radius: 31rpx;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        color: var(--a-one-text-color);

                        .iconfont {
                            font-size: 32rpx;
                        }
                    }

                    .active {
                        background: var(--a-main-color);
                    }
                }

                .right {
                    flex: 1;
                }
            }

            .create_btn {
                margin-top: 60rpx;
            }
        }
    }
}
</style>